//
//  uiTextureAtlas.cpp
//  trail-map-editor
//
//  Created by Giorgio Tino on 2/19/13.
//
//

#include "ui.h"

using namespace std;
using namespace tinyxml2;

uiTextureAtlas::uiTextureAtlas(const char* filename)
{
	Log.write(Debug, "Loading atlas %s.",filename);
	
    XMLDocument doc;
	doc.LoadFile(filename);
    
    // Read the root element: the 'imagePath' attribute contains the file name
    const XMLElement* root = doc.RootElement();
    
    const char* imagePath = root->Attribute("imagePath");
    
    if(!imagePath)
    {
        ulSetError(UL_FATAL, "Atlas file not specified in %s",filename);
        return;
    }
    
    // TBD : I need the texture info, but it looks like I'm loading the texture twice?
    ssgTextureInfo info;
	bool loaded = ssgLoadTexture(imagePath, &info);
	
    if(loaded)
    {
        float atlasWidth = info.width;
        float atlasHeight = info.height;
        
        // TODO : this could be optimized later
        atlasTexture = new ssgTexture(imagePath);
        
        // Parse all the subtextures and create the texture maps
        const XMLElement* subTextureElement = root->FirstChildElement();
        
        while(subTextureElement)
        {
            float height = subTextureElement->FloatAttribute("height");
            float width = subTextureElement->FloatAttribute("width");
            float y = subTextureElement->FloatAttribute("y");
            float x = subTextureElement->FloatAttribute("x");
            const char* name = ulStrDup(subTextureElement->Attribute("name"));
            
            // texture coords for this subtexture on the atlas.
            float left = x/atlasWidth;
            float bottom = y/atlasWidth;
            float right = left + width / atlasWidth;
            float top = bottom + height / atlasHeight;
			
			printf("--> %s : %f %f %f %f\n",name,left,bottom,right,top);
            
            uiTexture* subTexture = new uiTexture(name,atlasTexture,left,bottom,right,top);
            
            // TODO : check that the name does not exist!
            texturesMap[name] = subTexture;
            
            // Add the texture to the manager.
            uiTextureManager::getInstance().addTexture(name, subTexture);
            
            subTextureElement = subTextureElement->NextSiblingElement();
        }
    }
    else
    {
        ulSetError(UL_FATAL, "Cannot load atlas texture : %s",imagePath);
        return;
    }
}

uiTextureAtlas::~uiTextureAtlas()
{
    texturesMap.clear();
}

bool uiTextureAtlas::hasTexture(const char* name)
{
    uiTextureMap::const_iterator it = texturesMap.find(name);
    return it!=texturesMap.end();
}

uiTexture* uiTextureAtlas::getTexture(const char* name)
{
    uiTextureMap::const_iterator it = texturesMap.find(name);
    
    return it !=texturesMap.end() ? it->second : NULL;
}